package com.tanhua.server.controller;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import com.tanhua.common.service.PicUploadService;
import com.tanhua.common.vo.PageResult;
import com.tanhua.common.vo.PicUploadResult;
import com.tanhua.dubbo.server.pojo.SaveUserInfo;
import com.tanhua.server.service.UsersService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.Map;

/**
 * @author LOVE
 */
@RestController
@RequestMapping("/users")
public class UsersController {

    @Autowired
    private UsersService usersService;

    @Autowired
    private PicUploadService picUploadService;

    /**
     * 保存用户信息
     *
     * @param saveUserInfo 用户信息
     * @return 是否成功
     */
    @PutMapping
    public ResponseEntity<String> saveUserInformation(@RequestBody SaveUserInfo saveUserInfo) {
        //保存用户信息
        Boolean b = usersService.saveUserInformation(saveUserInfo);
        if (b) {
            return ResponseEntity.ok("修改成功!");
        }
        return ResponseEntity.ok("修改失败!");
    }

    /**
     * 获取用户信息
     *
     * @param userID    用户id
     * @param huanxinID 用户id
     * @return 是否成功
     */
    @GetMapping
    public SaveUserInfo getUserInformation(String userID, String huanxinID) {
        //如果id有值就根据id来,没有就获取token中的信息
        SaveUserInfo saveUserInfo = usersService.getUserInformation(userID, huanxinID);
        if (BeanUtil.hasNullField(saveUserInfo, "age")) {
            return null;
        }
        return saveUserInfo;
    }

    /**
     * 修改图片
     *
     * @param headPhoto 图片
     * @return 是否成功
     */
    @PostMapping("header")
    public ResponseEntity<String> editPicture(MultipartFile headPhoto) {
        PicUploadResult upload = picUploadService.upload(headPhoto);
        SaveUserInfo saveUserInfo = new SaveUserInfo();
        saveUserInfo.setAvatar(upload.getName());
        Boolean aBoolean = usersService.saveUserInformation(saveUserInfo);
        if (aBoolean) {
            return ResponseEntity.ok("保存成功");
        }
        return ResponseEntity.ok("保存失败!");
    }

    /**
     * 黑名单列表
     * @param page 当前页
     * @param pagesize 当前页数据条数
     * @return 是否成功
     */
    @GetMapping("blacklist")
    public PageResult blacklist(Integer page, Integer pagesize) {

        return usersService.blacklist(page, pagesize);
    }

    /**
     * 移出黑名单
     * @param toUserId 被移出的id
     * @return 是否成功
     */
    @DeleteMapping("blacklist/{uid}")
    public ResponseEntity<String> removeBlacklist(@PathVariable("uid") String toUserId){
        Boolean aBoolean = usersService.removeBlacklist(toUserId);
        if (aBoolean){
           return ResponseEntity.ok("成功!");
        }
        return ResponseEntity.ok("失败!");
    }
}
